import {
  encryptByAES,
  sha256,
  md5,
  newAESKey,
  encryptByRSA
} from './crypto'
// export const basePath = 'http://192.168.31.201:8080/shop'
export const basePath = 'https://shop.ldy.show/api'
// #ifdef H5
export const serviceURLs = [
	'/api' // 开发
]
// #endif
// #ifndef H5
export const serviceURLs = [
	basePath // 正式
]
// #endif
// 店id
export const shopCode = "root"
export const baseUrl = () => serviceURLs[uni.getStorageSync('config-url') || 0]
console.log('当前服务', baseUrl())
const {
	model,
	system,
	platform,
	deviceId,
	version,
	appid
} = uni.getStorageSync('config')
	
/**
 * 默认请求方式
 */
const request = (options = {}) => {
	// 在这里可以对请求头进行一些设置
	options.header = options.header || {}
	let token = uni.getStorageSync('token')
	if (token) {
		options.header['token'] = token;
	}
	if (!options.header['Content-Type']) {
		options.header['Content-Type'] = 'application/x-www-form-urlencoded';
	}
	
	
	Object.assign(options.header, {
		"Platform": platform,
		"OsVersion": system,
		"DeviceId": deviceId,
		"AppVersion": version,
		"AppName": appid
	})
	return new Promise((resolve) => {
		uni.request({
			url: baseUrl() + options.apiUri || '',
			method: options.type || 'GET',
			data: options.data || {},
			header: options.header || {},
			sslVerify: false
		}).then(data => {
			let [err, res] = data;
			console.log(err, res)
			if (res && res.data && (res.data.code === 30001 || res.data.code === 20001)) {
				uni.showToast({
					title: '用户长时间未操作，请重新登录',
					icon: "none"
				});
				uni.redirectTo({
					url: "/pages/login/login",
					success: () => {
						uni.removeStorageSync('token')
					}
				})
				// uni.reLaunch({
				// 	url: "/pages/login/login",
				// 	success: () => {
				// 		uni.removeStorageSync('token')
				// 	}
				// })
				return
			}
			if (!res ||  res.statusCode !== 200) {
				// #ifdef APP-PLUS
				if (options.cache && err.errMsg.indexOf('request:fail abort statusCode:-1') === 0) {
					// 需要缓存
					uni.showModal({
						title: '当前网络异常',
						content: '是否需要缓存数据？缓存数据后续将自动上报',
						success: (res) => {
							if (res.confirm) {
								console.log('用户点击确定');
								resolve({code: 9999});
							} else if (res.cancel) {
								console.log('用户点击取消');
								uni.showToast({
								    title: '操作取消',
								    icon: "none"
								});
								resolve({code: 30000, msg: err.errMsg});
								return
							}
						}
					});
					return
				}
				// #endif
				uni.showToast({
					title: '当前网络异常，请稍后再试',
					icon: "none"
				});
				resolve({code: 30000, msg: err.errMsg});
				return
			}
			if (res.data && res.data.code !== 20000) {
				uni.showToast({
					title: res.data.msg || '服务异常，请稍后再试',
					icon: "none"
				});
			}
			resolve(res.data);
		}).catch(error => {
			uni.showToast({
			    title: '服务异常，请稍后再试',
			    icon: "none"
			});
			// reject(error)
			resolve({code: 30000, msg: error});
		})
	});
}

/**
 * GET
 */
const get = (apiUri, data, options = {}) => {
	options.type = 'GET';
	options.data = data;
	options.apiUri = apiUri;
	return request(options)
}

/**
 * POST
 */
const post = (apiUri, data, options = {}) => {
	console.log('http=...', data)
	options.type = 'POST';
	options.data = data;
	options.apiUri = apiUri;
	return request(options)
}

/**
 * 安全post提交, 表单传参
 * 防重放+AES/RSA加密+签名
 * @param {String} apiUri api uri
 * @param {ObjectOrJsonString} params 请求参数，对象或json字符串
 */
const postSafe = (apiUri, params, options = {}) => {
	let token = uni.getStorageSync('token')
	let safeTag = createSafeTag(3)
	// aesKey:新建AES密钥
	let aesKey = newAESKey()
	// param:AES加密后的参数
	let param = encryptByAES(JSON.stringify(params), aesKey)
	// key:RSA公钥加密后的AES密钥
	let key = encryptByRSA(aesKey)
	// strForSign:待签名字符串
	let strForSign = apiUri + param + key + token + safeTag
	// sign:签名
	let sign = sha256(strForSign)
	let requestBody = {
		param,
		sign,
		key
	}
	options.type = 'POST';
	options.data = requestBody;
	options.apiUri = apiUri;
	options.header = {
		'SAFE-TAG': safeTag
	}
	return request(options)
}


/**
 * 创建安全标签, 安全等级;时间戳;防重放攻击的nonce, 例如：1;1551687809382;a411a616d438a...
 * @param {int} securityLevel 安全等级[0, 1, 2, 3], 如下：
 *    0:无, 1:防重放, 2:防重放+Base64编码+签名, 3:防重放+AES/RSA加密+签名
 * @return {string} 安全标签
 */
const createSafeTag = securityLevel => {
	if (!securityLevel) {
		return null
	}
	let mix = (Math.random() + '').substr(-5)
	let timestamp = new Date().getTime() + '-' + mix
	let nonce = md5(mix + ':' + securityLevel + ':' + timestamp)
	return securityLevel + ';' + timestamp + ';' + nonce
}


export {
	request,
	get,
	post,
	postSafe
}